package com.tiancheng.trade.settlement.util;

import com.tiancheng.trade.commom.core.utils.ServiceLocator;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 锁
 *
 * @author likail
 * @date 2021/06/16
 */
public final class Lock implements AutoCloseable {

    private RLock lock;
    private boolean lockRes;

    // 订单服务成功消息锁
    public static final String LOCK_ORDER_SUCCESS = "LOCK_ORDER_SUCCESS";

    public Lock(String region, String key, int waitTime, int leaseTime) throws Exception {
        this(region, key, waitTime, leaseTime, TimeUnit.SECONDS);
    }

    public Lock(String region, String key, int waitTime, int leaseTime, TimeUnit timeUnit) throws Exception {
        RedissonClient redissonClient = ServiceLocator.getBean(RedissonClient.class);
        StringBuilder name = new StringBuilder();
        name.append(region).append("_").append(key);
        lock = redissonClient.getLock(name.toString());
        lockRes = lock.tryLock(waitTime, leaseTime, timeUnit);
    }

    public boolean getLockRes() {
        return lockRes;
    }

    @Override
    public void close() throws Exception {
        if (lock != null) {
            lock.forceUnlock();
        }
    }
}
